﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace Recoveryflash
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    /// 

    // 1.定义委托
    public delegate void DelReadStdOutput(string result);
    public delegate void DelReadErrOutput(string result);

    public partial class MainWindow : Window
    {
        // 2.定义委托事件
        public event DelReadStdOutput ReadStdOutput;
        public event DelReadErrOutput ReadErrOutput;

        Process CmdProcess;
        string file = "";
        string mode = "";
        int count;
        StringBuilder flashoutput;

        public MainWindow()
        {
            InitializeComponent();
            Init();
        }
        private void Init()
        {
            //3.将相应函数注册到委托事件中
            ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);
            ReadErrOutput += new DelReadErrOutput(ReadErrOutputAction);

            progressBar.Visibility = Visibility.Hidden;
        }
        private void tb_file_TextChanged(object sender, TextChangedEventArgs e)
        {
            tb_file.IsEnabled = true;
            btn_connect.IsEnabled = true;
            if (tb_file.Text.Contains("img"))
            {
                tb_tips.Text = "已检测到img文件，接下来：\n\n" +
                    "1.请确保你已经解锁了BootLoader，重要！！！\n" +
                    "2.你需要安装官方的USB驱动，并关闭手机\n" +
                    "3.进入Fastboot模式（大部分系统为关机后同时按住音量下键 + 开机键开机，按住不放直到直到出现Fastboot界面）\n" +
                    "4.完成上述步骤，将手机连接到电脑,然后点击 [连接]";
            }

        }
        private void btn_open_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择将要输入的recovery文件";
            dialog.Filter = "img文件(*.img)|*.img";
            if (dialog.ShowDialog() == true)
            {
                file = dialog.FileName;
            }
            tb_file.Text = file;
        }
        private void btn_connect_Click(object sender, RoutedEventArgs e)
        {
            progressBar.Visibility = Visibility.Visible;
            btn_flash.IsEnabled = false;
            mode = "connect";
            tb_tips.Text = "连接中……";
            string cmdstr = "tools\\fastboot.exe devices";
            RunCmd(cmdstr);
        }

        //private void btn_start_Click(object sender, RoutedEventArgs e)
        //{
        //    progressBar.Visibility = Visibility.Visible;
        //    if (isDeviceReady())
        //    {
        //        tb_tips.Text = "设备已连接\n\n" +
        //            "确认要输入以下文件?\n"+
        //            file+
        //            "\n请点击 [刷入]";
        //        btn_flash.IsEnabled = true;  
        //    }
        //    else
        //    {
        //        tb_tips.Text = "设备未连接，请重试！\n\n"+
        //            "1.请确保你已经解锁了BootLoader，重要！！！\n" +
        //            "2.你需要安装官方的USB驱动，并关闭手机\n" +
        //            "3.同时按住音量下 + 开机键开机,按住不放直到显示米兔画面后松手,屏幕会始终停留在米兔LOGO界面\n" +
        //            "4.完成上述步骤，将手机连接到电脑,然后点击 [连接]";
        //    }
        //    progressBar.Visibility = Visibility.Hidden;
        //}

        private void btn_flash_Click(object sender, RoutedEventArgs e)
        {
            btn_flash.IsEnabled = false;
            flashoutput = new StringBuilder("");
            count = 0;
            tb_tips.Text = "正在刷入……";
            progressBar.Visibility = Visibility.Visible;
            mode = "flash";
            FlashRecovery();
            //if (FlashRecovery())
            //{
            //    tb_tips.Text = "刷入成功";
            //    btn_end.IsEnabled = true;
            //    //progressBar.Visibility = Visibility.Hidden;
            //}
            //else
            //{
            //    tb_tips.Text = "刷入失败，保留下方日志并加群（610047919）获取帮助";
            //    //progressBar.Visibility = Visibility.Hidden;
            //}
        }

        private void FlashRecovery()
        {
            //tools\fastboot.exe flash recovery recovery\recovery.img
            string cmdstr = "tools\\fastboot.exe flash recovery "+ file;
            RunCmd(cmdstr);
            //string successStr = "finished";
            //tb_result.AppendText("\n" + output);
            
            //tools\fastboot.exe boot recovery\recovery.img
            cmdstr = "tools\\fastboot.exe boot "+ file;
            RunCmd(cmdstr);

            //tb_result.AppendText("\n" + output);
            //return true;
            //return (output.Contains(successStr));
        }

        //private Boolean isDeviceReady()
        //{
        //    //string cmdstr = tb_cmdstr.Text.Trim();
        //    string cmdstr = "tools\\fastboot.exe devices";
        //    RunCmd(cmdstr);
        //    string successStr = "fastboot";
        //    tb_result.AppendText("\n" + output);
        //    return (output.Contains(successStr));  
        //}

        private void RunCmd(string cmdstr)
        {
            RealAction("cmd.exe", cmdstr);
        }

        private void RealAction(string StartFileName, string RunArg)
        {
            CmdProcess = new Process();
            CmdProcess.StartInfo.FileName = StartFileName;      // 命令
            //CmdProcess.StartInfo.Arguments = StartFileArg;      // 参数

            CmdProcess.StartInfo.CreateNoWindow = true;         // 不创建新窗口
            CmdProcess.StartInfo.UseShellExecute = false;
            CmdProcess.StartInfo.RedirectStandardInput = true;  // 重定向输入
            CmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
            CmdProcess.StartInfo.RedirectStandardError = true;  // 重定向错误输出
            //CmdProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            CmdProcess.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
            CmdProcess.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);

            CmdProcess.EnableRaisingEvents = true;                      // 启用Exited事件
            CmdProcess.Exited += new EventHandler(CmdProcess_Exited);   // 注册进程结束事件

            CmdProcess.Start();
            CmdProcess.StandardInput.WriteLine(RunArg);
            CmdProcess.BeginOutputReadLine();
            CmdProcess.BeginErrorReadLine();
            //CmdProcess.StandardInput.WriteLine("exit");

            // 如果打开注释，则以同步方式执行命令，此例子中用Exited事件异步执行。
            // CmdProcess.WaitForExit();     
        }

        private void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                // 4. 异步调用，需要invoke
                this.Dispatcher.Invoke(ReadStdOutput, new object[] { e.Data });

            }
        }

        private void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                this.Dispatcher.Invoke(ReadErrOutput, new object[] { e.Data });
            }
        }

        private void ReadStdOutputAction(string result)
        {
            UpdateUI(result);
            //tb_result.AppendText(result + "\r\n");

        }

        private void ReadErrOutputAction(string result)
        {
            UpdateUI(result);
            //tb_result.AppendText(result + "\r\n");
        }

        private void CmdProcess_Exited(object sender, EventArgs e)
        {
            // 执行结束后触发
        }
        private void UpdateUI(string result)
        {
            if (result.Trim()!=""&&mode.Equals("connect")) {
                if (result.EndsWith("fastboot"))
                {
                    tb_tips.Text = "设备已连接\n\n" +
                        "确认要刷入以下文件?\n" +
                        file +
                        "\n\n若确认刷入，请点击 [刷入]";
                    btn_flash.IsEnabled = true;
                    mode = "null";
                }
                else
                {
                    btn_flash.IsEnabled = false;
                    tb_tips.Text = "设备未连接，请重试！\n\n" +
                        "1.请确保你已经解锁了BootLoader，重要！！！\n" +
                        "2.你需要安装官方的USB驱动，并关闭手机\n" +
                        "3.进入Fastboot模式（大部分系统为关机后同时按住音量下键 + 开机键开机，按住不放直到直到出现Fastboot界面）\n" +
                        "4.完成上述步骤，将手机连接到电脑,然后点击 [连接]";
                }
                progressBar.Visibility = Visibility.Hidden;
              
            }
            else if (result.Trim() != "" && mode.Equals("flash"))
            {
                flashoutput.Append(result);
                if(result.Contains("finished"))
                    count++;
                if (count == 2)
                {
                    mode = "null";
                    btn_flash.IsEnabled = true;
                    if (flashoutput.ToString().Contains("FAILED"))
                    {
                        tb_tips.Text = "刷入失败，具体原因请查看下方日志\n\n" +
                            "可以加群：610047919，获取帮助（请一定要保留日志！）";
                    }                   
                    else if (flashoutput.ToString().Contains("OKAY"))
                    {
                        tb_tips.Text = "刷入成功,恭喜！\n\n" +
                            "手机将自动重启进入Recovery，请稍等……\n\n" +
                            "成功进入Recovery之后，你就可以关闭本程序并拔掉数据线啦";
                        btn_reboot.IsEnabled = false;
                        //progressbar.visibility = visibility.hidden;
                    }
                    progressBar.Visibility = Visibility.Hidden;
                }
            }

            tb_result.AppendText(result + "\r\n");
        }

        private void btn_logExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog();
            sf.Title = "保存日志文件";
            sf.DefaultExt = "txt";
            sf.Filter = "log 文件(*.log)|*.log|txt 文件 (*.txt)|*.txt|All files (*.*)|*.*";
            sf.FilterIndex = 1;
            sf.RestoreDirectory = true;
            if ((bool)sf.ShowDialog())
            {
                using (FileStream fs = new FileStream(sf.FileName, FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                    {
                        sw.Write(tb_result.Text);
                    }
                }

            }
        }

        private void btn_logClear_Click(object sender, RoutedEventArgs e)
        {
            tb_result.Text = "";
        }

        private void btn_reboot_Click(object sender, RoutedEventArgs e)
        {
            //fastboot reboot
            mode = "reboot";
            btn_flash.IsEnabled = false;
            tb_tips.Text = "正在尝试重启到主系统……";
            string cmdstr = "tools\\fastboot.exe reboot";
            RunCmd(cmdstr);
        }

        private void btn_help_Click(object sender, RoutedEventArgs e)
        {
            AboutBox aboutBox = new AboutBox();
            aboutBox.ShowDialog();
        }

        private void btn_qq_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://jq.qq.com/?_wv=1027&k=53jhvg8"); 
        }
    }
}
